﻿#include "FormDiary.h"
#include "DialogCalendar.h"

#include <QTGui>
#include <QTCore>

FormDiary::FormDiary(QWidget * parent, Qt::WFlags f): SubFrame(parent, f)
{
	QSplitter* sp = new QSplitter(this);
	sp->setOrientation(Qt::Horizontal);
	m_treeWidget = new QTreeWidget(sp);
	m_treeWidget->setIconSize(QSize(16, 16));
	m_treeWidget->setMaximumWidth(200);
	m_textEdit = new QTextEdit(sp);
	//m_textEdit->setFont(QFont("宋体", 12, QFont::Normal));
	QVBoxLayout* layoutTop = new QVBoxLayout(this);
	layoutTop->addWidget(sp);

	m_menuPop = new QMenu(this);
	QAction *act = m_menuPop->addAction(QIcon("./images/filenew.png"),tr("New Diary"));
	connect(act, SIGNAL(triggered()), this, SLOT(createDiary()));
	act = m_menuPop->addAction(QIcon("./images/filesave.png"),tr("Save"));
	connect(act, SIGNAL(triggered()), this, SLOT(saveDiary()));
	act = m_menuPop->addAction(QIcon("./images/delete.png"),tr("Delete"));
	connect(act, SIGNAL(triggered()), this, SLOT(deleteDiary()));

	connect( m_treeWidget,
			 SIGNAL( customContextMenuRequested (const QPoint &)), 
			 this, 
			 SLOT( showTreeMenu(const QPoint & ) ) );

	m_treeWidget->setContextMenuPolicy ( Qt::CustomContextMenu);
	connect( m_treeWidget,
			 SIGNAL( itemClicked ( QTreeWidgetItem * , int )), 
			 this, 
			 SLOT( treeClicked(QTreeWidgetItem*, int ) ) ) ;

	connect( m_textEdit,
			 SIGNAL( textChanged ()), 
			 this, 
			 SLOT( textChanged(void) ) ) ;

	m_strCurFileName = "";

	m_strList	<< tr("Sun")
				<< tr("Mon")
				<< tr("Tue")
				<< tr("Wed")
				<< tr("Thu")
				<< tr("Fri")
				<< tr("Sat");

	QStringList headerLabels;
    headerLabels << tr("Components");
	m_treeWidget->setHeaderLabels(headerLabels);
	m_treeWidget->header()->hide();

	m_modified = false;

	initTree(QDate::currentDate());
}

FormDiary::~FormDiary(void)
{
	saveDiary();
}

const QString FormDiary::m_strRoot = "./data/diary";


void FormDiary::initTree(const QDate& date)
{

	QString strY(tr("%1").arg(date.year()));
	QString strM(tr("%1").arg(date.month(),2,10,QChar('0')));
	QString strD(tr("%1").arg(date.day(),2,10,QChar('0')));

	m_treeWidget->clear();
	QDir yDir(FormDiary::m_strRoot);
	QFileInfoList yLst = yDir.entryInfoList();
	int iYear = 0;
	int iMonth = 0;
	int iDay = 0;
	for ( int i = 0; i < yLst.size(); i++)
	{
		if(yLst[i].fileName() == "." || yLst[i].fileName() == "..")
		{
			continue;
		}

		QTreeWidgetItem *yIt = new QTreeWidgetItem(m_treeWidget);
		yIt->setData(0, Qt::UserRole, tr(""));
		yIt->setText(0,yLst[i].fileName() + tr(""));
		yIt->setIcon(0,QIcon("./images/year.png"));

		if(strY == yLst[i].fileName())
		{
			m_treeWidget->expandItem(yIt);
		}

		iYear = yLst[i].fileName().toInt();

		QDir mDir(yLst[i].filePath());
		QFileInfoList mLst = mDir.entryInfoList();
		for ( int j = 0; j < mLst.size(); j++)
		{
			if(mLst[j].fileName() == "." || mLst[j].fileName() == "..")
			{
				continue;
			}
			QTreeWidgetItem *mIt = new QTreeWidgetItem(yIt);
			mIt->setData(0, Qt::UserRole, tr(""));
			mIt->setText(0,mLst[j].fileName() + tr(""));
			mIt->setIcon(0,QIcon("./images/month.png"));

			if(strM == mLst[j].fileName())
			{
				m_treeWidget->expandItem(mIt);
			}

			iMonth = mLst[j].fileName().toInt();

			QDir dDir(mLst[j].filePath());
			QFileInfoList dLst = dDir.entryInfoList();
			for ( int n = 0; n < dLst.size(); n++)
			{
				if(dLst[n].fileName() == "." || dLst[n].fileName() == "..")
				{
					continue;
				}
				QTreeWidgetItem *dIt = new QTreeWidgetItem(mIt);
				dIt->setData(0, Qt::UserRole, dDir.filePath(dLst[n].fileName()));
				iDay = dLst[n].baseName().toInt();
				
				QDate dtTmp(iYear, iMonth, iDay);

				int nTmp = dtTmp.dayOfWeek();
				
				if(nTmp == 7)
				{
					nTmp = 0;
				}

				dIt->setText(0,dLst[n].baseName() + tr(" ") + m_strList[nTmp]);
				dIt->setIcon(0,QIcon("./images/day.png"));		

				if(strD == dLst[n].baseName())
				{
					m_treeWidget->setItemSelected(dIt ,true);
					setCurFileName(dDir.filePath(dLst[n].fileName()));
					loadFile();
				}				
			}
		}
	}
}

void FormDiary::treeClicked(QTreeWidgetItem* item, int column)
{
	saveDiary();
	if(setCurFileName(item->data(0, Qt::UserRole).toString()))
	{
		loadFile();
	}
}

void FormDiary::showTreeMenu(const QPoint & pos)
{
	QPoint pg = m_treeWidget->mapToGlobal(pos);
	m_menuPop->exec(pg);
}

void FormDiary::createDiary(void)
{
	DialogCalendar form(this);
	int res = form.exec();

	if(QDialog::Accepted == res)
	{
		createDiary(form.date());		
		initTree(form.date());
	}
	else
	{
	}
}

void FormDiary::createDiary(const QDate& date)
{
	QDir yDir(FormDiary::m_strRoot);
	QString strY(tr("%1").arg(date.year()));
	QString strM(tr("%1").arg(date.month(),2,10,QChar('0')));
	QString strD(tr("%1").arg(date.day(),2,10,QChar('0')));

	
	if(!yDir.exists(strY))
	{
		yDir.mkdir(strY);
	}
	yDir.cd(strY);

	if(!yDir.exists(strM))
	{
		yDir.mkdir(strM);
	}
	yDir.cd(strM);

	strD += tr(".txt");
	QString name = yDir.filePath(strD);
	if(!yDir.exists(strD ))
	{
		QFile file(name);
		file.open(QFile::WriteOnly | QFile::Text);
		file.close();
	}
	else
	{
      QMessageBox::warning(this, tr("hello"),
                             tr("File Already Exists %1!")
                             .arg(name));                             
	}
}

bool FormDiary::setCurFileName(QString& name)
{
	if( m_strCurFileName == name )
	{
		return false;
	}
	else
	{
		 m_strCurFileName = name;
		 return true;
	}
}

void FormDiary::loadFile(void)
{
	if("" == m_strCurFileName)
	{
		return;
	}

    QFile file(m_strCurFileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("hello"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(m_strCurFileName)
                             .arg(file.errorString()));
        return;
    }

    QTextStream in(&file);
	in.setCodec(QTextCodec::codecForName("GB2312"));
    QApplication::setOverrideCursor(Qt::WaitCursor);
    m_textEdit->setPlainText(in.readAll());
    QApplication::restoreOverrideCursor();
	m_modified = false;
}

void FormDiary::saveDiary(void)
{
	if(	m_modified == false)
	{
		return;
	}
	if("" == m_strCurFileName)
	{
		return;
	}

    QFile file(m_strCurFileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("hello"),
                             tr("Cannot write file %1:\n%2.")
                             .arg(m_strCurFileName)
                             .arg(file.errorString()));
        return;
    }

    QTextStream out(&file);
	out.setCodec(QTextCodec::codecForName("GB2312"));
    QApplication::setOverrideCursor(Qt::WaitCursor);
    out << m_textEdit->toPlainText();
    QApplication::restoreOverrideCursor();
}

void FormDiary::save(void)
{
	saveDiary();
}

void FormDiary::fileNew(void)
{
	createDiary();
}

void FormDiary::open(void)
{
	DialogCalendar form(this);
	int res = form.exec();

	if(QDialog::Accepted == res)
	{
		if(isDiaryExist(form.date()))
		{

		}
		else
		{
			if(QMessageBox::question(this, tr("hello"),
						 tr("Diary already exists?"),
						 QMessageBox::Yes,
						 QMessageBox::No) == QMessageBox::Yes)
			{
				createDiary(form.date());
			}
			else
			{
				return;
			}
		}
		initTree(form.date());
	}
	else
	{
	}
}

bool FormDiary::isDiaryExist(const QDate& date)
{
	QDir yDir(FormDiary::m_strRoot);
	QString strY(tr("%1").arg(date.year()));
	QString strM(tr("%1").arg(date.month(),2,10,QChar('0')));
	QString strD(tr("%1").arg(date.day(),2,10,QChar('0')));

	
	if(!yDir.exists(strY))
	{
		yDir.mkdir(strY);
	}
	yDir.cd(strY);

	if(!yDir.exists(strM))
	{
		yDir.mkdir(strM);
	}
	yDir.cd(strM);

	strD += tr(".txt");
	QString name = yDir.filePath(strD);
	if(!yDir.exists(strD ))
	{
		return false;
	}
	else
	{
		return true;                            
	}
}

void FormDiary::fileDelete(void)
{
	deleteDiary();
}

void FormDiary::deleteDiary(void)
{
	if(QMessageBox::question(this, tr("hello"),
				 tr("Really Delete %1?").arg(m_strCurFileName),
				 QMessageBox::Yes,
				 QMessageBox::No) == QMessageBox::No)
	{
		return;
	}

	QDir yDir(".");
	if(yDir.remove(m_strCurFileName))
	{
	}
	else
	{
        QMessageBox::warning(this, tr("hello"),
                             tr("Fail to deltet file %1!")
                             .arg(m_strCurFileName));
		return;
	}

	initTree(QDate::currentDate());
}

void FormDiary::textChanged(void)
{
	m_modified = true;
}
